import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import { ElMessage } from 'element-plus'
import store from '../store'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView,
    },
    {
      path: '/user',
      name: 'userHome',
      component: () => import('../views/UserHomeView.vue'),
      // 配置是否需要认证
      meta: {
        requiresAuth: true,
        permissions: ['user:view', 'product:view'],
        roles: ['admin', 'user', 'merchant'],
      }
    },
    {
      path: '/profile',
      name: 'userProfile',
      component: () => import('../views/UserProfileView.vue'),
      meta: {
        requiresAuth: true,
        permissions: ['user:view', 'product:view'],
        roles: ['admin', 'user', 'guest', 'merchant'],
      }
    },
    {
      path: '/admin',
      name: 'adminView',
      component: () => import('../views/AdminView.vue'),
      meta: {
        requiresAuth: true,
        permissions: ['admin:view'],
        roles: ['admin']
      }
    },
    {
      path: '/merchant',
      name: 'merchantView',
      component: () => import('../views/MerchantView.vue'),
      meta: {
        requiresAuth: true,
        permissions: ['merchant:view'],
        roles: ['merchant','admin']
      }
    },
    {
      path: '/search',
      name: 'searchResult',
      component: () => import('../views/SearchResultView.vue'),
      meta: {
        requiresAuth: true,
        permissions: ['user:view', 'product:view'],
        roles: ['admin', 'user', 'guest', 'merchant']
      }
    },
    {
      path: '/orders',
      name: 'orderList',
      component: () => import('../views/OrderListView.vue'),
      meta: {
        requiresAuth: true,
        permissions: ['order:view'],
        roles: ['admin', 'user', 'merchant']
      }
    },
    {
      path: '/favorites',
      name: 'favoriteList',
      component: () => import('../views/FavoriteListView.vue'),
      meta: {
        requiresAuth: true,
        permissions: ['user:view'],
        roles: ['admin', 'user']
      }
    },
    {
      path: '/recently-viewed',
      name: 'recentlyViewed',
      component: () => import('../views/RecentlyViewedView.vue'),
      meta: {
        requiresAuth: true,
        permissions: ['user:view'],
        roles: ['admin', 'user']
      }
    },
    {
      path: '/product/:id',
      name: 'productDetail',
      component: () => import('../views/ProductDetailView.vue'),
      meta: {
        requiresAuth: true,
        permissions: ['user:view', 'product:view'],
        roles: ['admin', 'user', 'merchant']
      }
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 首先检查是否有token
    if (!store.getStore('token')) {
      ElMessage.error('请先登录')
      next({ name: 'login' })
      return
    }

    // 检查路由是否需要特定权限
    if (to.meta.permissions) {
      // 提取路径作为简化权限标识
      const pathPermission = to.path.split('/')[1] // 例如从'/user'提取'user'
      console.log("权限路径：" + pathPermission);

      // 检查用户是否有该路径的权限，或者有传统的权限列表中的权限
      const hasPermission = store.hasPermission(pathPermission) ||
        to.meta.permissions.some(permission =>
          store.hasPermission(permission)
        )

      if (!hasPermission) {
        ElMessage.error('您没有权限访问此页面')
        next({ name: 'userHome' })
        return
      }
    }

    // 检查路由是否需要特定角色
    if (to.meta.roles && !to.meta.roles.includes(store.state.role)) {
      ElMessage.error('您的角色无法访问此页面')
      next({ name: 'userHome' })
      return
    }
  }

  // 通过所有验证，允许访问
  next()
})

export default router
